﻿using AcexeService.Models;
using AcexeService.ServiceModel.Sys;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.OrmLite;
namespace AcexeService.ServiceInterface.Sys
{
    [Authenticate]
    public class SysPermissionsService : Service
    {
        /// <summary>
        /// 通过权限ID(PermissionId)取用户实体数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(GetSysPermission request)
        {
            string DicId = request.PermissionId;
            var list = Db.Select<SYS_PERMISSIONS>(c => c.PERMISSIONID == DicId);
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }
        /// <summary>
        /// 查询权限数据
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(GetSysPermissionList request)
        {
            var q = Db.From<SYS_PERMISSIONS>()
                .OrderBy(x => x.PERMISSIONID);
            var list = Db.Select<SYS_PERMISSIONS>(q);
            return list;
        }
        /// <summary>
        /// 新增字典
        /// </summary>
        /// <param name="requst"></param>
        /// <returns></returns>
        public object Any(AddSysPermission request)
        {
            var dto = new MessageDto();
            var model = request.SysPermissionModel;

            if (string.IsNullOrEmpty(model.PERMISSIONID))
            {
                dto.Flag = false;
                dto.Msg = "权限ID不允许为空";
                return dto;
            }
            if (string.IsNullOrEmpty(model.PERMISSIONNAME))
            {
                dto.Flag = false;
                dto.Msg = "权限名称不允许为空";
                return dto;
            }



            try
            {
                Db.Insert<SYS_PERMISSIONS>(model);
                dto.Flag = true;
                dto.Msg = "新增成功";
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public object Any(EditSysPermission request)
        {
            var dto = new MessageDto();
            var model = request.SysPermissionModel;

            if (string.IsNullOrEmpty(model.PERMISSIONID))
            {
                dto.Flag = false;
                dto.Msg = "权限ID不允许为空";
                return dto;
            }
            if (string.Equals(model.PERMISSIONNAME, ""))
            {
                dto.Flag = false;
                dto.Msg = "权限名称不允许为空";
                return dto;
            }


            try
            {
                var list = Db.Select<SYS_PERMISSIONS>(c => c.PERMISSIONID == model.PERMISSIONID);
                if (list.Count == 0)
                {
                    dto.Flag = false;
                    dto.Msg = "您编辑的记录不存在";
                    return dto;
                }

                var editmodel = list[0];

                editmodel = AcexeService.ServiceInterface.Lib.AutoTransfer.GetModel<SYS_PERMISSIONS>(editmodel, model);

                Db.Update<SYS_PERMISSIONS>(editmodel);
                dto.Flag = true;
                dto.Msg = "修改成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
            }
            return dto;
        }
        public object Any(DeleteSysPermission request)
        {
            var dto = new MessageDto();
            if (string.IsNullOrEmpty(request.SysPermissionId))
            {
                dto.Flag = false;
                dto.Msg = "空记录";
                return dto;
            }
            var id = request.SysPermissionId;
            //var i = Db.Select<SYS_PERMISSIONS_BTN>(c => c.PERMISSIONID == id).Count;
            //var j = Db.Select<SYS_PERMISSIONS_FUNC>(c => c.PERMISSIONID == id).Count;
            //var k = Db.Select<SYS_PERMISSIONS_USERGROUP>(c => c.PERMISSIONID == id).Count;

            var i = Db.Scalar<SYS_PERMISSIONS_BTN, int>(x => Sql.Count("*"), x => x.PERMISSIONID == id);
            var j = Db.Scalar<SYS_PERMISSIONS_FUNC, int>(x => Sql.Count("*"), x => x.PERMISSIONID == id);
            var k = Db.Scalar<SYS_PERMISSIONS_USERGROUP, int>(x => Sql.Count("*"), x => x.PERMISSIONID == id);
            if (i > 0 || j > 0 || k > 0)
            {
                dto.Flag = false;
                dto.Msg = "该权限无法删除";
                return dto;
            }

            try
            {

                //Db.Update<SYS_PERMISSIONS>(new { ISDELETED = false }, where: x => x.PERMISSIONID == id);
                Db.Delete<SYS_PERMISSIONS>(x => x.PERMISSIONID == id);
                dto.Flag = true;
                dto.Msg = "删除成功";
                return dto;
            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
                throw;
            }
        }

        ////////////////////////////////////

        public object Any(GetFunctionListByPermisId request)
        {
            var miniuigridmodel = new MiniUiGridModel<SYS_FUNCTION>();
            var model = request.SysFuncModel;

            var q = Db.From<SYS_FUNCTION>();


            q.Join<SYS_PERMISSIONS_FUNC>((a, b) => a.FUNCID == b.FUNCID);
            q.Where<SYS_PERMISSIONS_FUNC>(a => a.PERMISSIONID == request.PermissionId);

            if (!string.IsNullOrEmpty(request.FuzzyFuncName))
            {
                q.And(p => p.FUNCNAME.Contains(request.FuzzyFuncName));
            }

            q.And(x => x.ISDELETED == model.ISDELETED);

            if (!string.IsNullOrEmpty(model.FUNCNAME))
                q.And(x => x.FUNCNAME.Contains(model.FUNCNAME));

            if (!string.IsNullOrEmpty(model.FUNCDISPLAYNAME))
                q.And(x => x.FUNCDISPLAYNAME.Contains(model.FUNCDISPLAYNAME));

            if (!string.IsNullOrEmpty(model.FUNCURL))
                q.And(x => x.FUNCURL.Contains(model.FUNCURL));

            miniuigridmodel.total = Db.Scalar<int>(q.Select(Sql.Count("*")));

            if (!request.Page.IsGetWholeData)
            {
                q.Take(request.Page.PageSize);
                q.Skip(request.Page.PageSize * request.Page.PageIndex);
            }

            if (!string.IsNullOrEmpty(request.Page.SortField))
            {
                if (request.Page.SortOrder == "asc")
                    q.OrderByFields(request.Page.SortField);
                else
                    q.OrderByFieldsDescending(request.Page.SortField);
            }
            else
            {
                q.OrderBy(x => x.FUNCNAME);
            }

            var list = Db.Select<SYS_FUNCTION>(q.Select(c => c));
            var resultlist = list;
            miniuigridmodel.data = resultlist;

            return miniuigridmodel;
        }

        public object Any(GetUserGroupListByPermisId request)
        {
            var q = Db.From<SYS_PERMISSIONS_USERGROUP>();
            q.Join<SYS_USERGROUP>((a, b) => a.GROUPID == b.GROUPID);
            q.Where(a => a.PERMISSIONID == request.PermissionId);
            q.And<SYS_USERGROUP>(a => a.ISDELETED == false);
            return Db.Select<SYS_USERGROUP>(q); ;
        }

        public object Any(GetOrganizationListByPermisId request)
        {
            var q = Db.From<ORG_ORGANIZATION>()
              .LeftJoin<ORG_ORGANIZATION, SYS_PERMISSIONS_ORG>((a, b) => (a.ORGID == b.ORGID && b.PERMISSIONID == request.PermisId))
              .Where(x => x.ISDELETED == false)
              .OrderBy(x => x.ORDERNUM);

            if (!string.IsNullOrEmpty(request.CateId))
            {
                q.And(x => x.ORGCATE == request.CateId);
            }

            q.Select<ORG_ORGANIZATION, SYS_PERMISSIONS_ORG>((a, b) => new
            {
                a,
                CHECKED = "",
                b.PERMISSIONID
            });

            var list = Db.Select<Dictionary<string, object>>(q);

            for (int i = 0; i < list.Count; i++)
            {
                list[i]["CHECKED"] = list[i]["PERMISSIONID"] != null ? "checked" : "";
            }

            return list;
        }

        ///////////////////////////////////

        private void DealLeafPermisFunc(UpdatePermissionsFunction request)
        {
            if (request.IsChecked)
            {
                using (System.Data.IDbTransaction dbTrans = Db.OpenTransaction())
                {
                    Db.Delete<SYS_PERMISSIONS_FUNC>(new SYS_PERMISSIONS_FUNC
                    {
                        FUNCID = request.MenuId,
                        PERMISSIONID = request.PermisId
                    });
                    Db.Insert<SYS_PERMISSIONS_FUNC>(new SYS_PERMISSIONS_FUNC
                    {
                        FUNCID = request.MenuId,
                        PERMISSIONID = request.PermisId
                    });

                    dbTrans.Commit();
                }
            }
            else
            {
                Db.Delete<SYS_PERMISSIONS_FUNC>(new SYS_PERMISSIONS_FUNC
                {
                    FUNCID = request.MenuId,
                    PERMISSIONID = request.PermisId
                });
            }
        }

        private void GetChildrenList(List<SYS_MENU> source, string parentId, List<SYS_MENU> result)
        {
            result = result ?? new List<SYS_MENU>();
            var children = source.FindAll(c => c.MENUPARENTID == parentId);

            foreach (var item in children)
            {
                result.Add(item);
                GetChildrenList(source, item.MENUID, result);
            }
        }

        private void DealParentPermisFunc(UpdatePermissionsFunction request)
        {
            var result = new List<SYS_MENU>();
            var source = Db.Select<SYS_MENU>().OrderBy(c => c.MENUORDERNUM).Where(c => c.ISDELETED == false).Select(c => c);

            GetChildrenList(source.ToList(), request.MenuId, result);

            var children = result.Select(c => c.MENUID).ToList();

            using (System.Data.IDbTransaction dbTrans = Db.OpenTransaction())
            {

                for (int i = 0; i < children.Count; i++)
                {
                    string funcid = children[i];
                    Db.Delete<SYS_PERMISSIONS_FUNC>(new SYS_PERMISSIONS_FUNC
                    {
                        FUNCID = funcid,
                        PERMISSIONID = request.PermisId
                    });

                    if (request.IsChecked)
                    {
                        // 为使前端 tree 控件 正确显示，不许将有子菜单的菜单写进菜单权限表

                        bool hasChildMenu = result.Count(c => c.MENUPARENTID == funcid) != 0;

                        if (!hasChildMenu)
                        {
                            Db.Insert<SYS_PERMISSIONS_FUNC>(new SYS_PERMISSIONS_FUNC
                            {
                                FUNCID = funcid,
                                PERMISSIONID = request.PermisId
                            });
                        }
                    }
                }

                dbTrans.Commit();
            }
        }

        public object Any(UpdatePermissionsFunction request)
        {
            var dto = new MessageDto();
            try
            {
                if (request.IsLeaf)
                {
                    DealLeafPermisFunc(request);

                }
                else
                {
                    DealParentPermisFunc(request);
                }

                dto.Flag = true;
                dto.Msg = "操作成功";
                return dto;

            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }

        ///////////////////////////////////

        public object Any(UpdatePermissionsOrganization request)
        {
            var dto = new MessageDto();
            try
            {
                if (request.IsDeleted)
                {
                    Db.Delete<SYS_PERMISSIONS_ORG>(new SYS_PERMISSIONS_ORG
                    {
                        ORGID = request.OrgId,
                        PERMISSIONID = request.PermisId
                    });

                }
                else
                {
                    Db.Insert<SYS_PERMISSIONS_ORG>(new SYS_PERMISSIONS_ORG
                    {
                        ORGID = request.OrgId,
                        PERMISSIONID = request.PermisId
                    });
                }

                dto.Flag = true;
                dto.Msg = "操作成功";
                return dto;

            }
            catch (Exception ex)
            {
                dto.Flag = false;
                dto.Msg = ex.ToString();
                return dto;
            }
        }

    }
}
